package cn.dengta.webapp.trade.entity.meta;

import cn.dengta.webapp.trade.entity.meta.MetaConfig.MetaRuleConfig;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter;
import lombok.Setter;
import me.codeplayer.util.Assert;
import me.codeplayer.util.X;

/**
 * 邀请的规则配置对象
 */
@Getter
@Setter
public class InviteUserRule implements MetaRuleConfig {

	/** 充值比例 */
	public Integer rechargeRate;
	/** 积分收益比例 */
	public Integer incomeRate;
	/** 代理返点比例 */
	public Integer agentBelongRate;
	/** 奖励在途天数 */
	public Integer allocateDay;
	/** 注册奖励配置 */
	public RegisterEntry[] registerEntries;

	@Override
	public void validate() {
		Assert.isTrue(rechargeRate != null && rechargeRate >= 0 && rechargeRate <= 100, "充值比例大于等于0且不超过100！");
		Assert.isTrue(incomeRate != null && incomeRate >= 0 && incomeRate <= 100, "积分收益比例大于等于0且不超过100！");
		Assert.isTrue(agentBelongRate != null && agentBelongRate >= 0 && agentBelongRate <= 100, "代理返点比例大于等于0且不超过100！");
		Assert.isTrue(allocateDay != null && allocateDay > 0, "在途天数不能小于0！");
		final RegisterEntry[] entries = this.registerEntries;
		Assert.isTrue(X.size(entries) > 0, "注册奖励配置不能为空！");
		for (int i = entries.length - 1; i > 0; ) {
			RegisterEntry entry = entries[i--];
			entry.validate();
			RegisterEntry nextEntry = entries[i];
			nextEntry.validate();
			Assert.isTrue(entry.times > nextEntry.times, "注册人数只能递增！");
		}
	}

	@Override
	public void init(MetaRuleConfig config) {
		InviteUserRule rule = (InviteUserRule) config;
		this.rechargeRate = rule.rechargeRate;
		this.incomeRate = rule.incomeRate;
		this.agentBelongRate = rule.agentBelongRate;
		this.allocateDay = rule.allocateDay;
		this.registerEntries = rule.registerEntries;
	}

	@JSONField(serialize = false)
	public Integer getMaxCoin() {
		return X.isValid(registerEntries) ? registerEntries[registerEntries.length - 1].coin : null;
	}

	@JSONField(serialize = false)
	public Integer getCoin(Integer times, boolean defaultValue) {
		final RegisterEntry[] entries = this.registerEntries;
		for (int i = entries.length - 1; i >= 0; i--) {
			if (times >= entries[i].times) {
				return entries[i].coin;
			}
		}
		return defaultValue ? entries[0].coin : null;
	}

	/**
	 * 邀请注册规则实体
	 */
	@Setter
	@Getter
	public static class RegisterEntry {

		protected Integer times;
		protected Integer coin;

		public RegisterEntry(Integer times, Integer coin) {
			this.times = times;
			this.coin = coin;
		}

		public void validate() {
			Assert.isTrue(times > 0, "人数必须大于0！");
			Assert.isTrue(coin >= 0, "钻石必须大于0！");
		}

	}

}
